﻿Ext.namespace("Swfu");
Ext.namespace("Swfu.BackMgr");

Swfu.BackMgr.RolesMgr = Ext.extend(Ext.grid.EditorGridPanel,
{
    initComponent: function () {
        var Plant = Ext.data.Record.create([{ name: 'Name' }, { name: 'Description'}]);
        var sm = new Ext.grid.CheckboxSelectionModel();
        var fm = Ext.form;
        var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm,
        {
            header: "角色名称", sortable: true, dataIndex: 'Name', editor: new fm.TextField({
                allowBlank: false
            })
        },

        {
            header: "描述", sortable: true, dataIndex: 'Description', width: 400, editor: new fm.TextField({
                allowBlank: true
            })
        }]);
        var reader = new Ext.data.JsonReader(
        {
            totalProperty: "totalSize", autoLoad: true, fields: [{
                name: 'Id'
            },
            {
                name: 'Name'
            },
            {
                name: 'Description'
            }]
        });
        var ds = new Ext.data.Store(
        {
            scopte: this, url: '/roles.mvc/FindAll_roles', reader: reader, sortInfo: {
                field: 'Id', direction: "ASC"
            }
        });
        Ext.apply(this,
        {
            plain: true, layout: 'fit', border: false, cm: cm, sm: sm, frame: true, store: ds,
            loadMask: true, clicksToEdit: 1, tbar: [
            {
                text: '添加', iconCls: 'icon-edit',
                handler: function () {
                    var p = new Plant({
                        isNew: '1', 'Name': '', 'Description': ''
                    });
                    this.stopEditing();
                    ds.insert(0, p);
                    this.startEditing(0, 0)
                }
                .createDelegate(this)
            },
            '-',
            {
                text: '删除', id: 'delJiaoseBtn', iconCls: 'icon-delete', minWidth: '50',
                handler: function () {
                    var selections = this.selModel.getSelections();
                    var n = selections.length;
                    if (n == 0) {
                        Ext.Msg.alert("系统提示:", "请至少选择一项！");
                        return
                    }
                    Ext.Msg.show(
                    {
                        title: '系统确认', msg: '您是否确定删除此记录?删除的数据无法恢复！', buttons: Ext.Msg.YESNO, scope: this,
                        fn: function (btn) {
                            if (btn == 'yes') {
                                store = this.getStore();
                                var rds = [];
                                for (var i = 0; i < n; i++) {
                                    rds.push(selections[i].data);
                                    store.remove(selections[i])
                                }
                                var rdsjson = Ext.util.JSON.encode(rds);
                                this.deleteSelectedRows(rdsjson)
                            }
                        },
                        icon: Ext.MessageBox.QUESTION
                    })
                }
                .createDelegate(this)
            },
            '-',
            {
                text: "重新加载数据", iconCls: 'refreshicon',
                handler: function () {
                    ds.reload()
                }
                .createDelegate(this)
            },
            '-',
            {
                text: "授权", id: 'shouQuanBtn', iconCls: 'icon-edit',
                handler: function () {
                    QuanxianMgr(ds)
                }
                .createDelegate(this)
            },
            '-',
            {
                text: "保存", iconCls: 'icon-save',
                handler: function () {
                    var record;
                    var grid = this.getStore();
                    grid.each(function (rs) {
                        if (rs.get('isNew') == '1') {
                            record = rs;
                            if (rs.get('Name').trim.length <= 0) {
                                Ext.ux.Toast.msg('提示', '数据不完整，请重新输入...');
                                return
                            }
                            this.jsonData = Ext.util.JSON.encode(record.data);
                            Ext.Ajax.request(
                            {
                                url: '/roles.mvc/Add_roles',
                                success: function () {
                                    ds.reload();
                                    Ext.ux.Toast.msg('提示', '已经成功保存新添加的角色。')
                                },
                                failure: function () {
                                    Ext.Msg.alert("错误", "更新数据库失败,请重新操作.")
                                },
                                params: {
                                    jsJson: this.jsonData
                                },
                                waitMsg: '保存数据中...'
                            })
                        }
                        else if (rs.dirty) {
                            record = rs;
                            this.jsonData = Ext.util.JSON.encode(record.data);
                            Ext.Ajax.request(
                            {
                                url: '/roles.mvc/Update_roles',
                                success: function () {
                                    ds.reload();
                                    Ext.ux.Toast.msg('提示', '已经成功保存编辑的角色。')
                                },
                                failure: function () {
                                    Ext.Msg.alert("错误", "更新数据库失败,请重新操作.")
                                },
                                params: {
                                    jsJson: this.jsonData
                                },
                                waitMsg: '保存数据中...'
                            })
                        }
                    });
                    grid.commitChanges()
                }
                .createDelegate(this)
            }], loadMask: true
        });
        Swfu.BackMgr.RolesMgr.superclass.initComponent.apply(this, arguments);
        ds.load({
            params: {
                start: 0, limit: 15
            }
        })
    },
    deleteSelectedRows: function (rds) {
        var ds = this.getStore();
        Ext.Ajax.request(
        {
            url: '/roles.mvc/Del_roles',
            success: function (response, options) {
                var responseMessage = Ext.util.JSON.decode(response.responseText);
                if (responseMessage.Result) {
                    ds.reload();
                    Ext.ux.Toast.msg('提示', '已经成功删除选中的数据。')
                }
                else {
                    Ext.ux.Toast.msg('提示', '删除失败，请您重试。')
                }
            },
            failure: function (action) {
                if (action.failureType == 'server') {
                    obj = Ext.util.JSON.decode(action.response.responseText);
                    Ext.Msg.alert('错误:', obj.errors.reason)
                }
            },
            params: {
                jsJson: rds
            }
        })
    }
});

function QuanxianMgr(jsds) {
    var win;
    var FunSm = new Ext.grid.CheckboxSelectionModel();
    var RoleSm = new Ext.grid.CheckboxSelectionModel();
    var RoleFunSm = new Ext.grid.CheckboxSelectionModel();
    var FunCm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), FunSm, {
        header: '功能模块编号', dataIndex: 'funid', hidden: true
    },
    {
        header: '功能模块名称', dataIndex: 'funname', width: 95
    },

    {
        header: '子父节点', dataIndex: 'fatherid', width: 60,
        renderer: function (value) {
            if (value == "0") {
                return "<font color='blue'>父节点</font>";
            }
            else {
                return "<font color='red'>子节点</font>";
            }
        }
    }]);
    FunCm.defaultSortable = true;
    var FunReader = new Ext.data.JsonReader(
    {
        totalProperty: "totalSize", autoLoad: true, fields: [{
            name: 'funid'
        },
        {
            name: 'funname'
        },
        {
            name: 'fatherid'
        }]
    });
    var FunDs = new Ext.data.Store(
    {
        scopte: this, url: '/userfun.mvc/FindAll_userfun', reader: FunReader, sortInfo: {
            field: 'funid', direction: "ASC"
        }
    });
    FunDs.reload();
    var AllFunsGrid = new Ext.grid.GridPanel(
    {
        id: 'AllFunsGrid', border: true, ds: FunDs, cm: FunCm, sm: FunSm, height: 410, width: 215,
        plain: true, layout: 'fit', frame: true, loadMask: true
    });
    var RoleCm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), RoleSm, {
        header: 'ID', dataIndex: 'roleid', hidden: true
    },
    {
        header: '角色代码', dataIndex: 'roleno'
    },
    {
        header: '角色名称', dataIndex: 'rolename'
    }]);
    RoleCm.defaultSortable = true;
    var RolesGrid = new Ext.grid.GridPanel(
    {
        id: 'RolesGrid', border: true, ds: jsds, cm: RoleCm, sm: RoleSm, height: 190, width: 390,
        plain: true, layout: 'fit', frame: true, loadMask: true
    });
    var RoleFunCm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), RoleFunSm,
    {
        header: '角色名称', dataIndex: 'roleid',
        renderer: function (value, cellmeta, record) {
            var index = jsds.find('roleid', value);
            var record = jsds.getAt(index);
            if (record) {
                return record.data.rolename;
            }
        }
    },

    {
        header: '功能模块名称', dataIndex: 'funid',
        renderer: function (value, cellmeta, record) {
            var index = FunDs.find('funid', value);
            var record = FunDs.getAt(index);
            if (record) {
                return record.data.funname;
            }
        }
    },

    {
        header: '权限', dataIndex: 'rolep',
        renderer: function (value) {
            if (value == 0) {
                return '(0)读写';
            }
            if (value == 1) {
                return '(1)仅读';
            }
        }
    }]);
    RoleFunCm.defaultSortable = true;
    var RoleFunReader = new Ext.data.JsonReader({
        autoLoad: true, fields: [{
            name: 'pid'
        },
        {
            name: 'roleid'
        },
        {
            name: 'funid'
        },
        {
            name: 'rolep'
        }]
    });
    var RoleFunDs = new Ext.data.Store(
    {
        scopte: this, url: '/rolefun.mvc/FindRoleFun_rolefun', reader: RoleFunReader, sortInfo: {
            field: 'roleid', direction: "ASC"
        }
    });
    var str = -1;
    RoleFunDs.load({
        params: {
            roleid: str
        }
    });
    var RoleFunGrid = new Ext.grid.GridPanel(
    {
        id: 'RoleFunGrid', border: false, ds: RoleFunDs, cm: RoleFunCm, sm: RoleFunSm, height: 210,
        width: 390, plain: true, layout: 'fit', frame: true, loadMask: true, viewConfig: {
            forceFit: true
        },
        tbar: [
        {
            text: '功能模块授权', tooltip: '功能模块授权', iconCls: 'icon-edit',
            handler: function () {
                SetRoleFuns()
            }
        },
        '-',
        {
            text: '删除授权', tooltip: '删除授权', iconCls: 'icon-delete',
            handler: function () {
                DeleteRoleFun()
            }
        }]
    });
    var FunPannel = new Ext.Panel(
    {
        title: '功能模块', region: 'west', split: false, width: 215, collapsible: true, items: AllFunsGrid
    });
    var RolePannel = new Ext.Panel({
        title: '角色', collapsible: true, height: 200, items: RolesGrid
    });
    var RoleFunPannel = new Ext.Panel({
        title: '权限', collapsible: true, items: RoleFunGrid
    });
    var jsRoleFunPannel = new Ext.Panel({
        region: 'center', items: [RolePannel, RoleFunPannel]
    });
    if (!win) {
        win = new Ext.Window(
        {
            id: 'grid-win', title: '角色授权', shim: false, animCollapse: false, constrainHeader: true,
            closable: true, width: 620, height: 460, border: false, plain: true, iconCls: 'icon-roleMgr',
            layout: 'border', items: [FunPannel, jsRoleFunPannel]
        })
    }
    win.show();
    AllFunsGrid.addListener('rowcontextmenu', AllFunsGridRightClickFn);
    var mkRightClick = new Ext.menu.Menu({
        items: [{
            id: 'jsqxMenu1', handler: SetRoleFuns, text: '功能模块授权'
        }]
    });
    RoleFunGrid.addListener('rowcontextmenu', RoleFunGridRightClickFn);
    var qxRightClick = new Ext.menu.Menu(
    {
        items: [{
            id: 'readable', handler: setRoleFunReadable, text: '授权仅读'
        },
        {
            id: 'writeable', handler: setRoleFunWriteable, text: '授权读写'
        },
        {
            id: 'delBtn', handler: DeleteRoleFun, text: '删除授权'
        }]
    });
    RolesGrid.addListener('rowcontextmenu', RolesGridRightClickFn);
    var jsRightClick = new Ext.menu.Menu({
        items: [{
            id: 'jsglsqMenu1', handler: SetRoleFuns, text: '功能模块授权'
        }]
    });
    RolesGrid.getSelectionModel().on('rowselect', function (RoleSm, rowIdx, r) {
        str = r.data.roleid;
        RoleFunDs.load({
            params: {
                roleid: str
            }
        })
    });
    function AllFunsGridRightClickFn(AllFunsGrid, rowindex, e) {
        e.preventDefault();
        mkRightClick.showAt(e.getXY())
    }
    function RoleFunGridRightClickFn(RoleFunGrid, rowindex, e) {
        e.preventDefault();
        qxRightClick.showAt(e.getXY())
    }
    function RolesGridRightClickFn(RolesGrid, rowindex, e) {
        e.preventDefault();
        jsRightClick.showAt(e.getXY())
    }
    function setRoleFunReadable() {
        setRoleFunReadWrite(1)
    }
    function setRoleFunWriteable() {
        setRoleFunReadWrite(0)
    }
    function setRoleFunReadWrite(qx) {
        var selqx = RoleFunGrid.selModel.getSelections();
        var n = selqx.length;
        var qxrds = [];
        if (n > 0) {
            for (var i = 0; i < n; i++) {
                var arr = selqx[i].data;
                arr.rolep = qx;
                qxrds.push(arr)
            }
            var qxjson = Ext.util.JSON.encode(qxrds);
            Ext.Ajax.request(
            {
                url: '/rolefun.mvc/Update_rolefun',
                success: function () {
                    RoleFunDs.load({
                        params: {
                            roleid: str
                        }
                    });
                    Ext.ux.Toast.msg('提示', '已经成功修改权限。')
                },
                failure: function () {
                    Ext.Msg.alert("错误", "修改权限失败,请重新操作.")
                },
                params: {
                    json: qxjson
                },
                waitMsg: '保存数据中...'
            })
        }
        else {
            Ext.Msg.alert('错误', '请选择授权项！')
        }
    }
    function DeleteRoleFun() {
        var selqx = RoleFunGrid.selModel.getSelections();
        var n = selqx.length;
        var i = 0;
        var qxrds = [];
        if (n > 0) {
            for (var i = 0; i < n; i++) {
                qxrds.push(selqx[i].data)
            }
            var qxjson = Ext.util.JSON.encode(qxrds);
            Ext.Ajax.request(
            {
                url: '/rolefun.mvc/Del_rolefun',
                success: function () {
                    RoleFunDs.load({
                        params: {
                            roleid: str
                        }
                    });
                    Ext.ux.Toast.msg('提示', '已经成功删除权限。')
                },
                failure: function () {
                    Ext.Msg.alert("错误", "删除权限失败,请重新操作.")
                },
                params: {
                    json: qxjson
                },
                waitMsg: '删除数据中...'
            })
        }
        else {
            Ext.Msg.alert('错误', '请选择删除项！')
        }
    }
    function SetRoleFuns() {
        var selmk = AllFunsGrid.selModel.getSelections();
        var seljs = RolesGrid.selModel.getSelections();
        var n = selmk.length;
        var m = seljs.length;
        if (n == 0) {
            Ext.MessageBox.alert('错误', '请选择功能模块！');
            return
        }
        else {
            if (m == 0) {
                Ext.MessageBox.alert('错误', '请选择角色！');
                return
            }
            var rds = [];
            for (var i = 0; i < n; i++) {
                for (var j = 0; j < m; j++) {
                    RoleFunDs.clearFilter();
                    var index = RoleFunDs.findBy(function (record, id) {
                        return record.get('roleid') == seljs[j].data.roleid && record.get('funid') == selmk[i].data.funid;
                    });
                    if (index == -1) {
                        var arr = "({roleid:" + seljs[j].data.roleid + ",funid:" + selmk[i].data.funid + ",rolep:0})";
                        arr = eval(arr);
                        rds.push(arr)
                    }
                    else {
                        Ext.ux.Toast.msg('提示', "功能模块“" + selmk[i].data.funname + "”在此之前已经授权给角色“" + seljs[j].data.rolename + "”");
                        return
                    }
                }
            }
            if (rds == "") {
                return;
            }
            var rdsjson = Ext.util.JSON.encode(rds);
            Ext.Ajax.request(
            {
                url: '/rolefun.mvc/Add_rolefun',
                success: function () {
                    RoleFunDs.load({
                        params: {
                            roleid: str
                        }
                    });
                    Ext.ux.Toast.msg('提示', "功能授权成功")
                },
                failure: function () {
                    Ext.Msg.alert("错误", "添加权限失败,请重新操作.")
                },
                params: {
                    json: rdsjson
                },
                waitMsg: '添加数据中...'
            })
        }
    }
};

Ext.reg('rolesmgr', Swfu.BackMgr.RolesMgr);